package com.leonzhangxf.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * @author leonzhangxf
 */
public class NioClient {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();

        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);


        if (channel.connect(new InetSocketAddress("localhost", 8080))) {
            channel.register(selector, SelectionKey.OP_READ);
            channel.write(ByteBuffer.wrap("hello sever 1".getBytes(StandardCharsets.UTF_8)));
        } else {
            channel.register(selector, SelectionKey.OP_CONNECT);
        }

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey nextKey = keyIterator.next();
                keyIterator.remove();
                if (!nextKey.isValid()) {
                    continue;
                }
                if (nextKey.isConnectable()) {
                    SocketChannel socketChannel = (SocketChannel)nextKey.channel();
                    if (socketChannel.finishConnect()) {
                        socketChannel.write(ByteBuffer.wrap("hello sever 2".getBytes(StandardCharsets.UTF_8)));
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    }
                }
                if (nextKey.isReadable()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    SocketChannel socketChannel = (SocketChannel)nextKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    while (0 < socketChannel.read(buffer)) {
                        buffer.flip();
                        byte[] content = new byte[buffer.remaining()];
                        buffer.get(content);
                        stringBuilder.append(new String(content, StandardCharsets.UTF_8));
                        buffer.clear();
                    }
                    System.out.println(stringBuilder.toString());
                }
            }
        }
    }
}
